package com.celan.year2023.month07.day23;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Celan
 * @description TODO
 */
class Solution {
    public int trap(int[] height) {
        int ans = 0;
        Deque<Integer> stack = new LinkedList<>();
        int n = height.length;
        for (int i = 0; i < n; ++i) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                // 维护 [栈顶->栈底==小->大]
                // 若当前高度大于栈顶高度，则弹出，计算左侧雨水面积
                int top = stack.pop();
                if (stack.isEmpty()) break;
                // 上一个点下标
                int left = stack.peek();
                // 宽度
                int currWidth = i - left - 1;
                // 高度
                int currHeight = Math.min(height[left], height[i]) - height[top];
                ans += currWidth * currHeight;
            }
            stack.push(i);
        }
        return ans;
    }
}
